#!/bin/bash
# 项目清理脚本 - 删除不重要的文件，保留核心功能

echo "=== ESP32项目清理 - 删除冗余文件 ==="

# 创建备份目录
mkdir -p backup/removed_files

echo "📦 备份要删除的文件..."

# 1. 删除构建产物和临时文件
echo "🧹 清理构建文件..."
rm -rf build/
rm -rf dist/
rm -rf esp32_arduino_python.egg-info/
find . -name "__pycache__" -type d -exec rm -rf {} + 2>/dev/null || true
find . -name "*.pyc" -delete
find . -name "*.pyo" -delete

# 2. 备份并删除冗余的工具文件
echo "🔧 处理冗余工具文件..."

# arduino_esp32.py 与 esp32_arduino/core.py 功能重复
if [ -f "arduino_esp32.py" ]; then
    mv arduino_esp32.py backup/removed_files/
    echo "  ✅ 移除 arduino_esp32.py (功能已集成到esp32_arduino包)"
fi

# arduino_example.py 与 examples/ 目录重复
if [ -f "arduino_example.py" ]; then
    mv arduino_example.py backup/removed_files/
    echo "  ✅ 移除 arduino_example.py (examples目录已有完整示例)"
fi

# test_led.py 功能已被examples覆盖
if [ -f "test_led.py" ]; then
    mv test_led.py backup/removed_files/
    echo "  ✅ 移除 test_led.py (功能已集成到examples)"
fi

# build_and_flash.py 功能重复
if [ -f "build_and_flash.py" ]; then
    mv build_and_flash.py backup/removed_files/
    echo "  ✅ 移除 build_and_flash.py (使用pio命令即可)"
fi

# flash_esp32.py 功能重复
if [ -f "flash_esp32.py" ]; then
    mv flash_esp32.py backup/removed_files/
    echo "  ✅ 移除 flash_esp32.py (使用pio命令即可)"
fi

# 3. 清理旧的清理脚本
if [ -f "cleanup_project.sh" ]; then
    mv cleanup_project.sh backup/removed_files/
    echo "  ✅ 移除 cleanup_project.sh (功能已整合)"
fi

if [ -f "organize_project.sh" ]; then
    mv organize_project.sh backup/removed_files/
    echo "  ✅ 移除 organize_project.sh (功能已整合)"
fi

# 4. 处理重复的文档
echo "📚 整理文档文件..."

# 保留主要文档，移除重复的结构说明
if [ -f "项目结构说明.md" ]; then
    # 将重要信息合并到README中，然后删除
    mv "项目结构说明.md" backup/removed_files/
    echo "  ✅ 移除 项目结构说明.md (信息已整合到README)"
fi

# 5. 清理空目录
echo "📁 清理空目录..."
if [ -d "docs" ] && [ -z "$(ls -A docs)" ]; then
    rmdir docs
    echo "  ✅ 删除空的docs目录"
fi

if [ -d "protocol" ]; then
    mv protocol backup/removed_files/
    echo "  ✅ 移除protocol目录 (通信协议已文档化)"
fi

# 6. 清理backup中的旧文件
if [ -d "backup/old_files" ]; then
    rm -rf backup/old_files
    echo "  ✅ 清理旧备份文件"
fi

# 7. 检查并报告保留的核心文件
echo ""
echo "✅ 清理完成！保留的核心文件:"
echo ""
echo "📁 核心项目结构:"
echo "├── esp32-rk3588-sensor-system/    # ESP32固件和RK3588控制程序"
echo "├── esp32_arduino/                 # Python包源码"
echo "├── examples/                      # 示例代码"
echo "├── README.md                      # 项目主文档"
echo "├── setup.py                       # Python包配置"
echo "├── requirements.txt               # 依赖列表"
echo "├── LICENSE                        # 许可证"
echo "└── debug_serial.py                # 串口调试工具"
echo ""

# 统计文件数量
total_files=$(find . -type f -not -path "./esp_venv/*" -not -path "./backup/*" | wc -l)
echo "📊 当前项目文件总数: $total_files"

echo ""
echo "🎯 项目已精简，保留核心功能："
echo "  ✅ ESP32固件开发环境"
echo "  ✅ Arduino风格Python库"
echo "  ✅ 完整示例代码"
echo "  ✅ 详细文档"
echo "  ✅ 调试工具"
echo ""
echo "🗂️ 删除的文件已备份到: backup/removed_files/"
echo "如需恢复，可从备份目录中找回"